﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace CWM.Client.Converters
{
    /// <summary>
    /// bool 转换器 true:1 false:0
    /// </summary>
    public partial class BooleanConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            int? val = System.Convert.ToInt32(value);

            //如果val是空，取parameter做为默认值
            if (val == null)
            {
                if (parameter != null)
                {
                    return System.Convert.ToBoolean(parameter);
                }
            }

            if(val == null)
            {
                return null;
            }
            else if (val == 0)
            {
                return false;
            }
            else if (val == 1)
            {
                return true;
            }
            else
            {
                return null;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && value is bool)
            {
                return (bool)value == true ? 1 : 0;
            }
            return null;
        }
    }
}
